package com.itjianren.employeemanagementsystem.service.impl;

import com.itjianren.employeemanagementsystem.dto.EmployeeQueryDTO;
import com.itjianren.employeemanagementsystem.dto.PageResult;
import com.itjianren.employeemanagementsystem.mapper.EmployeeMapper;
import com.itjianren.employeemanagementsystem.model.Employee;
import com.itjianren.employeemanagementsystem.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> findAll() {
        return employeeMapper.findAll();
    }

    @Override
    public Employee findById(Integer id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void insert(Employee employee) {
        employeeMapper.insert(employee);
    }

    @Override
    public void update(Employee employee) {
        employeeMapper.update(employee);
    }

    @Override
    public void delete(Integer id) {
        employeeMapper.delete(id);
    }

    @Override
    public PageResult<Employee> findByCondition(EmployeeQueryDTO queryDTO) {
        PageResult<Employee> pageResult = new PageResult<>();

        // 计算分页参数
        int pageNum = queryDTO.getPageNum();
        int pageSize = queryDTO.getPageSize();
        int offset = (pageNum - 1) * pageSize;
        queryDTO.setOffset(offset);

        // 查询数据
        List<Employee> records = employeeMapper.findByCondition(queryDTO);
        int total = employeeMapper.countByCondition(queryDTO);

        // 计算总页数
        int pages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;

        // 设置分页结果
        pageResult.setRecords(records);
        pageResult.setTotal(total);
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setPages(pages);

        return pageResult;
    }
}